require("drw");
local type_table = {
    int = 4,
    short = 2,
    byte = 1,
    int8 = 1,
    int16 = 2,
    int32 = 4,
    float = 4,
    double = 8,
};

local function write_float(m,offset,size,float)
    dwfloat(m,offset,float);
end

local function write_double(m,offset,size,double)
    print(offset,double);
    dwdouble(m,offset,double);
end

function toArray(a,typ)
    local write = dw;
    local read = dr;
    local typName = typ;
    ----------------------------------
    --[[
        mm = dpointer(a);
        错误,metatable 大概是基于指针映射,所有会发现一些错误， 如 
        a = toArray(x,"int");  
        b = toArray(x,"char");   
        a[0] = 10;   --此时的a 是  char* 变量，而不是 int* ,所以需要把lightuserdata 转为userdata
        
    ]]
    --mm = dpointer(a);
    ----------------------------------    
    mm = touserdata(a);
    if(type(typ)=="string")then
        if(typ=="float")then
            write = write_float;
            read = drfloat;
        elseif(typ=="double")then
            write = write_double;
            read = drdouble;
        end
        typ = type_table[typ];
    end;
    if(typ==nil)then typ = 1 end;
    local metatable = {
        __index = function(m,k)
            return read(m,k*typ,typ);
        end,
        __newindex = function(m,k,v)
            return write(m,k*typ,typ,v);
        end,
        __add = function(m,v2)
            local p = dpointer(m,v2*typ);
            return toArray(p,typName);
        end,
    };
    udsetmetatable(mm,metatable);
    return mm;
end
